package com.omg.api.handle;

import java.util.List;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.omg.api.argument.Argument;
import com.omg.api.argument.FriendArgument;
import com.omg.api.result.Result;
import com.omg.api.result.body.FriendBody;
import com.omg.api.result.header.FriendHeader;
import com.omg.constant.ResponseCode;
import com.omg.persistence.dao.lifepoint.entity.LPUser;
import com.omg.persistence.delegate.lifepoint.LPUserDelegate;

/**
 * 
 * @author xiazhiquan
 * 
 *         May 29, 2011
 */
public class FriendHandler extends Handler {

	private static final Logger LOG = Logger.getLogger(FriendHandler.class
			.getName());

	private static FriendHandler instance = null;

	static {
		instance = new FriendHandler();
	}

	public static FriendHandler getInstance() {
		return instance;
	}

	public String handle(Argument argument) throws Exception {

		String userid = ((FriendArgument) argument).getUserid();

		List<LPUser> friends = LPUserDelegate.getInstance()
				.getLPFriendsByUserid(userid);

		return getJson(friends);
	}

	private final String getJson(List<LPUser> friends) throws Exception {
		try {

			// construct result
			Result result = new Result();

			// header
			FriendHeader header = new FriendHeader();
			header.setRespcode(ResponseCode.AP_E_Succ);
			result.setHeader(header);

			// body
			FriendBody body = new FriendBody();
			body.setFriends(friends);
			result.setBody(body);

			return new Gson().toJson(result);
		} catch (Exception e) {
			e.printStackTrace();
			String errorMsg = e.getMessage();
			LOG.error(errorMsg, e);
			throw new Exception(""
					+ (errorMsg != null && !errorMsg.isEmpty() ? errorMsg
							: ResponseCode.AP_E_Info_UnkownError));
		}
	}

}
